import { getPhone, getToken, getUserInfo, getUsername, removeToken, setPhone, setToken, setUserInfo, setUsername } from '@/utils/auth'
import { userInfo, logout, authorizations } from '@/api/user'

const state = {
  token: getToken(),
  phone: getPhone(),
  userInfo: getUserInfo(),
  userName: getUsername()
}

const mutations = {
  'SET_TOKEN' (state, token) {
    setToken(token)
    state.token = token
  },
  'REMOVE_TOKEN' () {
    removeToken()
  },
  'SET_PHONE' (state, phone) {
    setPhone(phone)
    state.phone = phone
  },
  'SER_USERNAME' (state, userName) {
    setUsername(userName)
    state.userName = userName
  },
  'SET_USER_INFO' (state, info) {
    setUserInfo(info)
    state.userInfo = info
  },
  'LOGOUT' (state) {
    setUserInfo('')
    removeToken()
    setPhone('')
    setUsername('')
    state.userInfo = ''
    state.token = ''
    state.phone = ''
    state.setUsername = ''
  }
}

const actions = {
  userInfo ({ commit }, data) {
    return new Promise((resolve, reject) => {
      try {
        userInfo(data).then(res => {
          console.log(res)
          setUsername(res.company_name)
          if (res.status === 1) {
            commit('SET_USER_INFO', res)
            resolve(res)
          }
        })
      } catch (e) {
        reject(e)
      }
    })
  },
  logout ({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        commit('LOGOUT')
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  getToken ({ commit }) {
    return new Promise((resolve, reject) => {
      authorizations().then(res => {
        commit('SET_TOKEN', res.access_token)
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
